#pragma once

#include <iostream>
#include <memory>
#include <unistd.h>
#include <sys/poll.h>
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

class PollServer
{
    const static int size = 4096;
    const static int defaultfd = -1;

public:
    PollServer(int port) : _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(port);
        for (int i = 0; i < size; i++)
        {
            _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listensock->Fd();
        _fds[0].events = POLLIN; // 让内核帮我关心_listenfd的可读事件
    }
    void Start()
    {
        int timeout = 100;
        _isrunning = true;
        while (_isrunning)
        {
            // 是为了实现单线程同时处理多个连接，避免为每个连接都创建一个线程或进程
            // 提高服务器的并发性能和资源利用率。
            int n = poll(_fds, size, timeout);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                LOG(LogLevel::DEBUG) << "有事件就绪了...";
                Dispatcher(); // 处理已经就绪事件
                break;
                // 死循环打印,因为没有处理需要调用accept系统调用
            }
        }
        _isrunning = false;
    }
    // 链接管理器
    void Accepter()
    {
        InetAddr client;
        int fd = _listensock->Accept(&client); // 不会阻塞,因为客户端事件已经就绪
        if (fd >= 0)
        {
            // 获取新链接成功
            LOG(LogLevel::INFO) << "get a new link, sockfd: "
                                << fd << ", client is: " << client.StringAddr();

            int pos = 0;
            for (; pos < size; pos++)
            {
                if (_fds[pos].fd == defaultfd)
                    break;
            }
            if (pos == size)
            {
                LOG(LogLevel::WARNING) << "select server  is full";
                close(fd);
            }
            else
            {
                _fds[pos].fd == fd;
                _fds[pos].events = POLLIN;
                _fds[pos].revents = 0;
            }
        }
    }
    // 事件派发器
    void Dispatcher()
    {
        // 读事件就绪
        for (int i = 0; i < size; i++)
        {
            if (_fds[i].fd == defaultfd)
                continue;
            // fd合法不一定代表读事件就绪
            if (_fds[i].events & POLLIN)
            {
                // 读事件就绪了
                // listenfd和普通sockfd都是读事件就绪,如何区分呢?
                if (_fds[i].fd == _listensock->Fd())
                {
                    // listenfd 新连接到来
                    Accepter();
                }
                else
                {
                    // 普通读事件已经就绪
                    Recver(i);
                }
            }
            // else if(_fds[i].events&POLLOUT)
            // {}

            // if(FD_ISSET(fd_array[i],&wfds))
            // {
            //     //
            // }
        }
    }
    // IO处理器
    void Recver(int pos)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[pos].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@ " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client quit...";
            close(_fds[pos].fd);
            _fds[pos].fd = defaultfd; // 让select不再关心该文件描述符
            _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
        else
        {
            //注意:_fds[pos].fd = defaultfd;   // 先重置标识
            //close(_fds[pos].fd);// 此时close的是defaultfd，原fd泄漏！
            LOG(LogLevel::ERROR) << "recv error";
            close(_fds[pos].fd);
            _fds[pos].fd = defaultfd;
            _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
    }
    void PrintFd()
    {
        std::cout << "_fds[]: ";
        for (int i = 0; i < size; i++)
        {
            if (_fds[i].fd == defaultfd)
                continue;
            std::cout << _fds[i].fd << " ";
        }
        std::cout << "\r\n";
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~PollServer()
    {
    }

private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;

    struct pollfd _fds[size];
};
